<template>
	<view class="share-code">
		<image :src="imgsrc" style="width: 215px; height: 215px;"></image>
	</view>
</template>

<script setup lang="ts">
	import { computed, ref } from 'vue'
	import {onShow, onHide} from "@dcloudio/uni-app"
	import { homeServer, vipServer } from "@/common/index"
	import { useBound } from "@/hooks/useBound.ts"
	import { useNotLogged } from "@/hooks/useNotLogged.ts"
	import { global, mock } from "@/utils/index.ts"
	const {tipBoundStudent, studentIsEmpt} = useBound();
	const { isNotLogged, tipToLogin } = useNotLogged()
	
	const shareCodeVal = ref(null)
	const imgsrc = ref("")
	
	const generatescheme = async (shareCode) => {
		try{
			const { status, data} = await vipServer.shareQRCode({shareCode})
			if(status === '200'){
				imgsrc.value = data
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	//  获取sharecode
	const queryShareCode = async () => {
		try{
			const {data, status} = await homeServer.remainMoneyAndSharecode()
			if(status === '200'){
				// shareCodeVal.value =  data.sharecode
				generatescheme(data.sharecode)
			}
		}catch(e){
			console.log(e)
			//TODO handle the exception
		}
	}
	
	
	const arrayBufferToBase64 = (buffer) => {
	      let binary = '';
	      const bytes = new Uint8Array(buffer);
	      const len = bytes.byteLength;
	      for (let i = 0; i < len; i++) {
	        binary += String.fromCharCode(bytes[i]);
	      }
	      return window.btoa(binary);
	}
	  
	
	const  downloadImage = ({shareCode}) =>{
	      uni.request({
	        url: 'https://your-backend-api.com/image', // 替换为你的后端接口地址
	        method: 'POST',
			data: {
				shareCode
			},
	        responseType: 'arraybuffer', // 设置响应类型为二进制数据
	        success: (res) => {
	          if (res.statusCode === 200) {
	            // 下载成功，保存图片到本地
	            uni.saveFile({
	              tempFilePath: 'data:image/jpeg;base64,' + arrayBufferToBase64(res.data),
	              success: (saveRes) => {
	                // saveRes.savedFilePath;
	              },
	              fail: (err) => {
	                console.error('保存图片失败', err);
	              }
	            });
	          } else {
	            console.error('下载图片失败', res);
	          }
	        },
	        fail: (err) => {
	          console.error('请求失败', err);
	        }
	      });
	  }
		  

	
	onShow(async () => {
		if(!mock.isLogged()){
			 tipToLogin()
		} 
		await queryShareCode()
	})
		
	
</script>

<style>
	page{
		/* background-color: #eff8fd; */
	}
	.share-code{
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>
